﻿using UnityEngine;
using UnityEngine.EventSystems;

[RequireComponent(typeof(Rigidbody2D))]
public class DragableRigidbody2D : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    public Camera UICamera;
    private Vector3 offset;
    private Rigidbody2D rigidbody2d; //2D物体的刚体组件

    private void Start()
    {
        rigidbody2d = transform.GetComponent<Rigidbody2D>(); //获取2D刚体组件
    }

    public void OnBeginDrag(PointerEventData eventData)
    {
        offset = Vector3.zero;
    }

    public void OnDrag(PointerEventData eventData)
    {
        Vector2 cursorPos = UICamera.ScreenToWorldPoint(Input.mousePosition); //获取鼠标的世界坐标
        if (Vector2.Distance(cursorPos, transform.position) < 1) //控制拖拽距离，防止拖拽过快穿墙
            rigidbody2d.MovePosition(cursorPos); //改变刚体坐标，符合物理规律
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        offset = Vector3.zero;
    }
}